<template>
	<page-wraper :safeAreaInsetBottom="true">
		<view>
			<wd-notice-bar text="订单包裹上限为5个, 包裹左滑屏幕删除或修改" prefix="warn-bold" />
			
			<wd-swipe-action v-for="(item, index) in packages" :key="index">
				<wd-cell :title="`包裹${index + 1}`"
					:value="`${item.length}×${item.width}×${item.height} cm - ${item.weight} lbs`" />
				<template #right>
					<view class="action">
						<view class="button delete" @click="() => remove(index)">删除</view>
						<view class="button edit" @click="() => edit(index, item)">编辑</view>
					</view>
				</template>
			</wd-swipe-action>
		</view>

		<wd-action-sheet v-model="showEditModal" title="编辑包裹">
			<wd-form ref="form2" :model="editRow" :rules="rules">
				<wd-cell-group border>
					<wd-input type="digit" label="长" label-width="100px" prop="length" v-model="editRow.length"
						placeholder="请输入长度">
						<template #suffix>
							<span>cm</span>
						</template>
					</wd-input>
					<wd-input type="digit" label="宽" label-width="100px" prop="width" v-model="editRow.width"
						placeholder="请输入宽度">
						<template #suffix>
							<span>cm</span>
						</template>
					</wd-input>
					<wd-input type="digit" label="高" label-width="100px" prop="height" v-model="editRow.height"
						placeholder="请输入高度">
						<template #suffix>
							<span>cm</span>
						</template>
					</wd-input>
					<wd-input type="digit" label="重量" label-width="100px" prop="weight" v-model="editRow.weight"
						placeholder="请输入重量">
						<template #suffix>
							<span>lbs</span>
						</template>
					</wd-input>
				</wd-cell-group>

				<view class="button-group">
					<wd-button type="info" plain @click="cancelEdit">取消</wd-button>
					<wd-button type="primary" @click="confirmEdit">确认</wd-button>
				</view>
			</wd-form>
		</wd-action-sheet>
		
		<wd-tabbar fixed bordered safeAreaInsetBottom placeholder v-if="packages.length < 5 && !showEditModal">
			<wd-button icon="add" block @click="add">添加包裹</wd-button>
		</wd-tabbar>
	</page-wraper>
</template>

<script lang="ts" setup>
	import { ref, watch } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import type { FormItemRule } from 'wot-design-uni'

	interface Package {
		id : string;
		length : string | number;
		width : string | number;
		height : string | number;
		weight : string | number;
		dims_unit ?: string;
		weight_unit ?: string;
	}

	const packages = ref<Package[]>([]);
	const orderType = ref('OLD');
	const editIndex = ref<number>(-1);
	const editRow = ref<Package>({
		id: '',
		length: '',
		width: '',
		height: '',
		weight: ''
	});
	
	onLoad((query: any) => {
		packages.value = JSON.parse(decodeURIComponent(query.packages));
		orderType.value = query.orderType;
		
		uni.onKeyboardHeightChange((res) => {
			console.log(res);
		});
	});
	
	const lb2kg = (val) => {
		return val * 0.45359237;
	}
	
	const dimValidator = (value) => {
		if (!value) return Promise.resolve();
	
		value = Number(value) || 0;
	
		var array = [Number(editRow.value.length) || 0, Number(editRow.value.width) || 0, Number(editRow.value.height) || 0];
	
		array.sort((a, b) => b - a);
	
		if (value <= 0) {
			return Promise.reject(new Error('请输入正确的数字'));
		} else if (orderType.value === 'OLD' && value > 120) {
			return Promise.reject(new Error('最大长度不能超过120CM'));
		} else if (orderType.value === 'NEW' && value > 100) {
			return Promise.reject(new Error('最大长度不能超过100CM'));
		} else if (orderType.value === 'OLD' && array[0] + 2 * (array[1] + array[2]) > 266) {
			return Promise.reject(new Error('（最长边(CM) + (第二边长(CM) + 第三边长(CM)) * 2）不能超过266'));
		} else if (orderType.value === 'NEW' && array[0] + 2 * (array[1] + array[2]) > 210) {
			return Promise.reject(new Error('（最长边(CM) + (第二边长(CM) + 第三边长(CM)) * 2）不能超过210'));
		}
	
		return Promise.resolve();
	}
	
	const weightValidator = (value) => {
		if (!value) return Promise.resolve();
		
		value = lb2kg(Number(value) || 0);
	
		if (value <= 0) {
			return Promise.reject(new Error('请输入正确的数字'));
		} else if (orderType.value === 'OLD' && value > 30) {
			return Promise.reject(new Error('重量不能超过30KG'));
		} else if (orderType.value === 'NEW' && value > 3) {
			return Promise.reject(new Error('重量不能超过3KG'));
		}
		
		return Promise.resolve();
	}
	
	// 修改表单验证规则部分，添加类型定义
	const rules : Record<string, FormItemRule[]> = {
		length: [
			{ required: true, message: '请输入长度' },
			{ required: true, validator: (val : string | number) => validateNumber(val, '长度') },
            {
				required: true, 
                message: '超出限制',
                validator: dimValidator
            }
		],
		width: [
			{ required: true, message: '请输入宽度' },
			{ required: true, validator: (val : string | number) => validateNumber(val, '宽度') },
            {
				required: true, 
                message: '超出限制',
                validator: dimValidator
            }
		],
		height: [
			{ required: true, message: '请输入高度' },
			{ required: true, validator: (val : string | number) => validateNumber(val, '高度') },
            {
				required: true, 
                message: '超出限制',
                validator: dimValidator
            }
		],
		weight: [
			{ required: true, message: '请输入重量' },
			{ required: true, validator: (val : string | number) => validateNumber(val, '重量') },
            {
				required: true, 
                message: '超出限制',
                validator: weightValidator
            }
		]
	};
	const showEditModal = ref(false);
	const form2 = ref();
	
	watch(packages, (newVal) => {
		uni.$emit('changePackages', newVal);
	}, { deep: true });

	function add() {
		editRow.value.id = (new Date().getTime()).toString();
		showEditModal.value = true;
	}

	function edit(index : number, item : any) {
		editIndex.value = index;
		editRow.value = { ...item };
		showEditModal.value = true;
	}

	function remove(index : number) {
		packages.value.splice(index, 1);
	}

	// 修改验证函数的返回类型
	const validateNumber = (value : string | number, type : string) : boolean | string => {
		const num = Number(value);
		if (isNaN(num)) {
			return `请输入正确的${type}`;
		}
		if (num <= 0) {
			return `${type}必须大于0`;
		}
		return true;
	};

	// 修改 confirmEdit 函数
	async function confirmEdit() {
		await form2.value.validate().then(({ valid } : { valid : boolean }) => {
			if (valid) {
				const packageData = {
					dims_unit: 'cm',
					weight_unit: 'lbs',
					length: Number(editRow.value.length),
					width: Number(editRow.value.width),
					height: Number(editRow.value.height),
					weight: Number(editRow.value.weight)
				};

				if (editIndex.value !== -1) {
					packages.value[editIndex.value] = packageData;
					editIndex.value = -1;
				} else {
					packages.value.push(packageData);
				}
				showEditModal.value = false;
				editRow.value = {
					length: '',
					width: '',
					height: '',
					weight: ''
				};
			}
		}).catch(() => {
			uni.showToast({
				title: '请输入正确的内容',
				icon: 'none'
			});
		});
	}

	function cancelEdit() {
		showEditModal.value = false;
		editRow.value = {
			length: '',
			width: '',
			height: '',
			weight: ''
		};
		editIndex.value = -1;
	}
</script>

<style lang="scss" scoped>
	:deep(.page-wraper) {
		background: #f6f6f6;
	}

	.button-group {
		display: flex;
		justify-content: space-around;
		padding: 20px;

		:deep(.wd-button) {
			width: 40%;
		}
	}

	.package-info {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		font-size: 14px;
		color: #666;

		text {
			display: block;
			line-height: 1.4;

			&:last-child {
				color: #999;
				font-size: 12px;
			}
		}
	}

	.action {
		display: flex;
		height: 100%;

		.button {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 80px;
			color: #fff;
			font-size: 14px;

			&.delete {
				background-color: #fa4350; // 红色
			}

			&.edit {
				background-color: #4d80f0; // primary蓝色
			}
		}
	}
</style>